import time
import logging
import schedule
from datetime import datetime
from sensors.dht22_sensor import DHT22Sensor
from sensors.light_sensor import LightSensor
from sensors.bmp280_sensor import BMP280Sensor
from services.weather_service import WeatherService
from services.ai_service import AIService
from services.audio_service import AudioService
from utils.data_processor import DataProcessor
from config.config import SENSOR_READ_TIMES, SENSOR_READ_INTERVAL

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('clothing_assistant.log'),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)

class ClothingAssistant:
    def __init__(self):
        self.dht22 = DHT22Sensor()
        self.light = LightSensor()
        self.bmp280 = BMP280Sensor()
        self.weather = WeatherService()
        self.ai = AIService()
        self.audio = AudioService()
        self.last_light_status = None
        
    def check_light_and_process(self):
        """检查光照并处理"""
        if not DataProcessor.is_morning_time():
            return
            
        current_light = self.light.is_bright()
        
        # 如果是从暗变亮，触发处理流程
        if self.last_light_status is False and current_light is True:
            logger.info("检测到光照变化：从暗变亮，开始处理...")
            self.process_and_report()
            
        self.last_light_status = current_light
        
    def process_and_report(self):
        """处理数据并播报"""
        try:
            # 读取室内数据
            logger.info("开始读取室内传感器数据...")
            temp, humidity = self.dht22.read_average(
                times=SENSOR_READ_TIMES,
                interval=SENSOR_READ_INTERVAL
            )
            bmp_data = self.bmp280.read_average(
                times=SENSOR_READ_TIMES,
                interval=SENSOR_READ_INTERVAL
            )
            
            indoor_data = DataProcessor.process_sensor_data(
                temp, humidity, bmp_data['pressure']
            )
            
            if not indoor_data:
                logger.error("室内数据获取失败")
                return
                
            # 获取室外数据
            outdoor_data = self.weather.get_weather()
            if not outdoor_data:
                logger.error("室外数据获取失败")
                return
                
            # 获取AI建议
            is_weekend = DataProcessor.is_weekend()
            advice = self.ai.get_clothing_advice(
                indoor_data,
                outdoor_data,
                is_weekend
            )
            
            # 播报建议
            logger.info(f"准备播报建议: {advice}")
            self.audio.speak(advice)
            
        except Exception as e:
            logger.error(f"处理过程出错: {str(e)}")
            
    def cleanup(self):
        """清理资源"""
        try:
            self.dht22.cleanup()
            self.light.cleanup()
        except Exception as e:
            logger.error(f"清理资源时出错: {str(e)}")

def main():
    assistant = None
    try:
        logger.info("启动智能穿衣助手...")
        assistant = ClothingAssistant()
        
        # 每秒检查光照状态
        schedule.every(1).seconds.do(assistant.check_light_and_process)
        
        while True:
            schedule.run_pending()
            time.sleep(1)
            
    except KeyboardInterrupt:
        logger.info("程序被用户中断")
    except Exception as e:
        logger.error(f"程序运行出错: {str(e)}")
    finally:
        if assistant:
            assistant.cleanup()
        logger.info("程序已停止")

if __name__ == "__main__":
    main()